<template>
  <div class="customer-table-box">
    <PlainCreateBtn v-if="hasRouteAuth('crm:customer:edit')" :class="{'mobile-contact-btn': showMobilePage}" class="add-btn" @click="handleAddContact">新建联系人</PlainCreateBtn>
    <el-table
      v-if="contactData.length > 0"
      ref="customerTableRef"
      :data="contactData"
      beautify-table
      header-drag-style
      use-virtual
      class="fb-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="order-data-header-cell"
      fit
      hightlight-current-row>
      <el-table-column width="140" align="left" label="客户联系人">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.contactPerson" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="联系方式" width="200">
        <template slot-scope="scope">
          <ToolTip v-if="scope.row['showSecret']" :content="scope.row.tel" />
          <div v-else>
            <span v-if="scope.row.tel.length <= 2">***********</span>
            <span v-else>{{ `${scope.row.tel[0]}*********${scope.row.tel[scope.row.tel.length - 1]}` }}</span>
            <el-button type="text" style="color: #406EFF; font-size: 14px" @click="handleCheckSecretVal(scope.row)">点击查看</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            :disabled="!hasRouteAuth('crm:customer:edit')"
            active-color="#406EFF"
            inactive-color="#cccccc"
            @change="switchStatus(scope.row, $event)"
          />
        </template>
      </el-table-column>
      <el-table-column align="left" label="协作人">
        <template slot-scope="scope">
          <ToolTip :content="formatName(scope.row.associate, 'userName')" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="协作部门">
        <template slot-scope="scope">
          <ToolTip :content="formatName(scope.row.coDepartment, 'name')" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建人">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.creator" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="所属部门" width="180">
        <template slot-scope="scope">
          <ToolTip :content="formatName(scope.row.department, 'name')" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建时间" width="180">
        <template slot-scope="scope">
          <ToolTip :content="standardFormat(scope.row.createTime / 1000, 'YYYY/MM/DD HH:mm:ss')" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="备注">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.remark" />
        </template>
      </el-table-column>
      <el-table-column v-if="hasRouteAuth('crm:customer:edit') || hasRouteAuth('crm:customer:deleteContact')" width="90" fixed="right" align="left" label="操作">
        <template slot-scope="scope">
          <div v-if="!showMobilePage" style="display:flex;">
            <div v-if="hasRouteAuth('crm:customer:edit')" class="button-text mr10" @click="handleEdit(scope.row)">编辑</div>
            <div v-if="hasRouteAuth('crm:customer:deleteContact')" class="button-text" @click="handleDel(scope.row)">删除</div>
          </div>
          <tableOperateBtn v-else>
            <el-dropdown-item v-if="hasRouteAuth('crm:customer:edit')" style="width:90px;text-align: center" @click.native="handleEdit(scope.row)">
              <div>编辑</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="hasRouteAuth('crm:customer:deleteContact')" style="width:90px;text-align: center" @click.native="handleDel(scope.row)">
              <div>删除</div>
            </el-dropdown-item>
          </tableOperateBtn>
        </template>
      </el-table-column>
    </el-table>
    <EmptyPlaceholder v-else :empty-img-top="'0px'" />
    <el-row type="flex" justify="end">
      <el-pagination
        v-show="contactDataCount > 0"
        :current-page="contactParams.page"
        :page-size="contactParams.perPage"
        :total="contactDataCount"
        :page-sizes="[10, 50, 100, 250, 500]"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <AddContactDialog ref="AddContactDialog" :customer-id="customerId" @updateDetail="updateDetail"/>
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import AddContactDialog from './addContactDialog';
import { getClientContacts, editContactStatus, checkClientPhone, deleteContact } from '@/api/customer';
import { standardFormat } from '@/filters/date';
import ElMessage, { showModal } from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import { formatName } from '@/utils/tools';
import { mapState } from 'vuex';
import mobileTable from '@/mixins/mobileTable';

export default {
  name: 'ContactTable',
  components: { AddContactDialog, EmptyPlaceholder },
  mixins: [mobileTable],
  props: {
    customerId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      contactLoading: false,
      contactData: [], // 联系人列表数据
      contactDataCount: 0,
      contactParams: {
        page: 1,
        perPage: 10
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  created() {
    this.getContactList();
  },
  methods: {
    hasRouteAuth,
    standardFormat,
    formatName,
    getContactList(resetPage) {
      this.contactLoading = true;
      if (resetPage) {
        this.contactParams.page = 1;
      }
      getClientContacts(this.customerId, this.contactParams).then(res => {
        if (res.code === 200) {
          this.contactData = res.data.items;
          this.contactDataCount = res.data.total;
          this.contactLoading = false;
        }
      }).catch(err => {
        console.log(err);
        this.contactLoading = false;
      });
    },
    handleAddContact() {
      this.$refs.AddContactDialog.openDialog();
    },
    handleSizeChange(val) {
      this.contactParams.perPage = val;
      this.getContactList();
    },
    handleCurrentChange(val) {
      this.contactParams.page = val;
      this.getContactList();
    },
    // 查看联系方式
    handleCheckSecretVal(rowData) {
      const rowIndex = this.contactData.findIndex(item => item.id === rowData.id);
      if (rowIndex === -1) {
        this.$message.warning('无法识别联系人id');
        return;
      }
      checkClientPhone(rowData.id).then(() => {
        this.$set(this.contactData[rowIndex], 'showSecret', true);
      });
    },
    switchStatus(row, status) {
      showModal(`请确认是否${status ? '启用' : '禁用'}该联系人？`, '', {}, true).then(_ => {
        editContactStatus(row.id, status).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功');
            this.getContactList();
            this.$emit('updateLog');
          }
        }).catch(_ => {
          row.status = status ? 0 : 1;
        });
      }).catch(_ => {
        row.status = status ? 0 : 1;
      });
    },
    handleEdit(row) {
      this.$refs.AddContactDialog.openDialog(row);
    },
    handleDel(row) {
      showModal(`请确认是否删除该联系人？`, '', {}, true).then(_ => {
        deleteContact(row.id).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功');
            this.getContactList();
            this.$emit('updateLog');
          }
        }).catch();
      }).catch(_ => {});
    },
    updateDetail() {
      this.getContactList(true);
      this.$emit('updateLog');
    }
  }
};
</script>
<style lang="scss" scoped>
.add-btn {
  top: -38px !important;
  border-radius: 4px;
}
.mr10 {
  margin-right: 10px;
}
</style>
